package top.syfy.spb.upload.imageandwatermark.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.syfy.spb.upload.imageandwatermark.constant.ContentReturnEnum;
import top.syfy.spb.upload.imageandwatermark.constant.UploadImageEnum;
import top.syfy.spb.upload.imageandwatermark.constant.WatermarkEnum;
import top.syfy.spb.upload.imageandwatermark.model.dto.ImageInfo;
import top.syfy.spb.upload.imageandwatermark.response.ContentReturnType;
import top.syfy.spb.upload.imageandwatermark.service.ImageUploadService;
import top.syfy.spb.upload.imageandwatermark.service.WatermarkService;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

/**
 * 图片上传应用层
 *
 * @author awg
 * @date 2020/10/23 星期五
 */
@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    /**
     * 与操作系统相关的文件名分隔符
     */
    final String separator = File.separator;

    @Autowired
    private ImageUploadService imageUploadServiceImpl;

    @Autowired
    private WatermarkService watermarkServiceImpl;

    /**
     * 上传图片的存储路径
     */
    @Value("${spbuiw.upload-dir}")
    private String UPLOAD_DIR;

    /**
     * 允许上传图片的格式
     */
    @Value("${spbuiw.allowed-image-suffix}")
    private String ALLOWED_IMAGE_SUFFIX;

    /**
     * 图片上传
     *
     * @param img 上传的图片
     * @return 上传图片的响应信息
     */
    @PostMapping(value = "/watermarkImg")
    public ContentReturnType upload(@RequestParam("img") MultipartFile img) throws IOException {
        // 文件的原始名称
        String originName = img.getOriginalFilename();
        // 图片格式检查
        String suffix = Objects.requireNonNull(originName).substring(originName.lastIndexOf(".") + 1).toUpperCase();
        if (!Arrays.asList(ALLOWED_IMAGE_SUFFIX.split(", *")).contains(suffix)) {
            return ContentReturnType.ofReturn(ContentReturnEnum.ILLEGAL_IMAGE, null);
        }

        ImageInfo info = new ImageInfo();
        // 上传图片
        info.setUploadedImageUrl(imageUploadServiceImpl.uploadImage(img, UPLOAD_DIR));
        // 添加水印
        // 服务器中水印图片的物理存储路径
        String watermarkImgPath = Objects.requireNonNull(this.getClass().getClassLoader().getResource(UploadImageEnum.getEnumValueByName("UPLOADED_IMAGE_RELATIVE_PATH"))).getPath() + File.separator + WatermarkEnum.getEnumValueByName("WATERMARK_FILE_NAME");
        info.setWatermarkedImageUrl(watermarkServiceImpl.watermarkAdd(new File(UPLOAD_DIR, originName), watermarkImgPath));

        return ContentReturnType.ofReturn(ContentReturnEnum.SUCCESS, info);
    }

}
